<template>
  <ElFormItem
    :label="titleText(options, item)"
    :prop="[childIndex, 'value']"
    :rules="{
      required: item.isRequired === 'Y',
      message: '请上传',
      trigger: 'change',
    }"
    class="flex_column"
  >
    <p v-if="options.showDesc" class="desc f12 mb10">
      {{ options.description }}
    </p>
    <ElUpload
      v-model:file-list="fileList"
      :accept="options.isType ? options.fileTypes : '[*]'"
      :auto-upload="false"
      :disabled="type === 'view'"
      :limit="options.limit || 1"
      :on-change="onChange"
      :on-exceed="onExceed"
      :on-preview="onPreview"
      :on-remove="beforeDelete"
      class="pc_upload"
      drag
      placeholder="请选择"
    >
      <ElIcon class="el-icon--upload">
        <UploadFilled />
      </ElIcon>
      <div class="el-upload__text">拖拽文件到此处 或者<em>点击这里</em></div>
    </ElUpload>
  </ElFormItem>
</template>

<script setup>
import { titleText } from "@/utils/common.js";
import { UploadFilled } from "@element-plus/icons-vue";
import { ElFormItem, ElIcon, ElMessage, ElUpload } from "element-plus";
import { ref, } from "vue";

//defineOptions({ name: "PCFileUpload" });

const { item, type, index, childIndex } = defineProps([
  "item",
  "type",
  "index",
  "childIndex",
]);
const emits = defineEmits(["change"]);
const { options } = JSON.parse(item.vformJson);
const fileList = ref(item.value);
const fileSize = options.fileMaxSize || 5;
// 文件变动
const onChange = (file, files) => {
  let type = file.name.split(".").pop().toLowerCase();
  let bool = false;
  if (options.isType && options.fileTypes.indexOf("." + type) === -1) {
    ElMessage.error(`请上传 ${(options.fileTypes || []).join(",")} 格式文件`);
    bool = true;
  }
  if (file.size > fileSize * 1024 * 1024) {
    ElMessage.error("文件大小不能超过 " + fileSize + "M");
    bool = true;
  }
  if (bool) {
    let len = fileList.value.length - 1;
    fileList.value.splice(len, 1);
  } else {
    change(files);
  }
};
// 超出文件上传个数
const onExceed = () => {
  ElMessage.error("您最多可以上传" + options.limit + "个文件");
};
// 传递值改变后
const change = (files) => {
  item.value = files || fileList.value;
  emits("change", item);
};
// 删除
const beforeDelete = () => {
  change();
};
// 点击文件列表中已上传的文件时的钩子
const onPreview = (uploadFile) => {
  type === "view" && window.open(uploadFile.url);
};
</script>
<style lang="less" scoped>
.pc_upload {
  width: 320px;
}
</style>